package Controller.CourseServlet;

import Dao.CourseDao;
import Dao.SCDao;
import bean.Course;
import bean.SC;
import bean.Student;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/course_delete")
public class course_delete extends HttpServlet {
    CourseDao courseDao = new CourseDao();
    SCDao scDao = new SCDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String cno = req.getParameter("cno");
        boolean flag = Boolean.parseBoolean(req.getParameter("flag"));
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        if (cno != null && cno.length() > 0) {
            if (flag) {
                courseDao.delete(cno);
                map.put("msg", "删除成功");
            } else {
                ArrayList<SC> scList = scDao.selectByCno(cno);

                if (scList != null && scList.size() > 0) {
                    map.put("code", 400);
                    map.put("msg", "该课程已已有学生选择，是否删除？");
                } else {
                    courseDao.delete(cno);
                    map.put("msg", "删除成功");
                }
            }
        } else {
            map.put("code", 401);
            map.put("msg", "请输入学号");
        }
        resp.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
